package logic

import (
	"context"
	"errors"
	"hema/models"

	"hema/hemarpc/hemarpc"
	"hema/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductAddLogic) ProductAdd(in *hemarpc.ProductAddRequest) (*hemarpc.ProductAddResponse, error) {
	// todo: add your logic here and delete this line

	tx := models.DB.Debug().Begin()

	var findProduct models.Product
	tx.Where("name = ?", in.Name).Find(&findProduct)
	if findProduct.ID != 0 {
		return nil, errors.New("已存在该商品")
	}

	var class models.Class
	tx.Where("name = ?", in.ClassName).Find(&class)

	if class.ID == 0 {
		class = models.Class{
			Name: in.ClassName,
		}
		err := tx.Create(&class)

		if err != nil {
			tx.Rollback()
			return nil, errors.New("商品添加失败")
		}
	}

	product := models.Product{
		Name:    in.Name,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		Image:   in.Image,
		Info:    in.Info,
		ClassId: int64(class.ID),
	}

	err := tx.Create(&product).Error
	if err != nil {
		tx.Rollback()
		return nil, errors.New("商品添加失败")
	}

	return &hemarpc.ProductAddResponse{
		ProductId: int64(product.ID),
	}, nil
}
